package edu.sandau.basic.controller;

import edu.sandau.basic.domain.User;
import edu.sandau.basic.domain.stumsg;
import edu.sandau.basic.global.GlobalEnum;
import edu.sandau.basic.service.StumsgService;
import edu.sandau.basic.service.UserService;
import edu.sandau.basic.vo.BasicMsg;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name="Stumsg")
public class StumsgController {
    @Resource
    private StumsgService stumsgService;
    
    @Resource
    private UserService userService;
    
    @PostMapping("/stumsg")
    @Operation(summary = "Create a new task with valid username.")
    public BasicMsg createStumsg(@RequestBody stumsg stumsg) {
        BasicMsg msg = new BasicMsg();
        try {
            GlobalEnum.ErrorCode errorCode = stumsgService.createStumsg(stumsg);
            msg.setErrorCode(errorCode);
            if(errorCode == GlobalEnum.ErrorCode.OK) {
                msg.setErrorMsg("创建任务成功。");
                msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
            } else if (errorCode == GlobalEnum.ErrorCode.USER_QUERY_FAILED) {
                // 需要检查具体是哪种错误
                String username = stumsg.getUsername();
                String taskName = stumsg.getMasname();
                
                if (username == null || username.trim().isEmpty()) {
                    msg.setErrorMsg("创建任务失败：用户名不能为空。");
                } else if (taskName == null || taskName.trim().isEmpty()) {
                    msg.setErrorMsg("创建任务失败：任务名称不能为空。");
                } else {
                    // 检查用户是否存在
                    try {
                        edu.sandau.basic.domain.User user = userService.getUserByUsername(username);
                        if (user == null) {
                            msg.setErrorMsg("创建任务失败：用户名不存在。");
                        } else {
                            // 用户存在，可能是任务名称重复
                            msg.setErrorMsg("创建任务失败：该用户下已存在同名任务。");
                        }
                    } catch (Exception e) {
                        msg.setErrorMsg("创建任务失败：未知错误。");
                    }
                }
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            } else {
                msg.setErrorMsg("创建任务失败。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            }
        } catch (Exception e) {
            // 检查是否是唯一键约束违反异常
            if (e.getCause() instanceof java.sql.SQLIntegrityConstraintViolationException) {
                msg.setErrorCode(GlobalEnum.ErrorCode.USER_QUERY_FAILED);
                msg.setErrorMsg("创建任务失败：任务名称已存在。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.UNKNOWN);
                msg.setErrorMsg("服务器异常: " + e.toString());
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            }
        }
        return msg;
    }
    
    @GetMapping("/stumsg")
    @Operation(summary = "Get all tasks by username.")
    public BasicMsg getStumsgByUsername(@RequestParam String username) {
        BasicMsg msg = new BasicMsg();
        try {
            List<stumsg> taskList = stumsgService.getStumsgByUsername(username);
            if (taskList != null && !taskList.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.OK);
                msg.setErrorMsg("查询成功。");
                msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
                msg.setData(taskList);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.USER_QUERY_FAILED);
                msg.setErrorMsg("未找到用户名为 " + username + " 的任务。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.UNKNOWN);
            msg.setErrorMsg("服务器异常: " + e.toString());
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        }
        return msg;
    }

    @DeleteMapping("/stumsg")
    @Operation(summary = "Delete task by username and name (masname).")
    public BasicMsg deleteStumsgByUsernameAndName(@RequestParam String username, @RequestParam String name) {
        BasicMsg msg = new BasicMsg();
        try {
            // 先查询该用户的所有任务
            System.out.println("查询用户 " + username + " 的所有任务");
            List<stumsg> taskList = stumsgService.getStumsgByUsername(username);
            System.out.println("找到 " + (taskList == null ? 0 : taskList.size()) + " 个任务");
            if (taskList != null) {
                for (stumsg task : taskList) {
                    System.out.println("任务: " + task.getMasname());
                }
            }
            if (taskList == null || taskList.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.USER_QUERY_FAILED);
                msg.setErrorMsg("未找到用户名为 " + username + " 的任务。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
                return msg;
            }
            
            // 不在这里设置所有任务列表，稍后只返回更新后的任务
            
            // 执行删除操作
            GlobalEnum.ErrorCode result = stumsgService.deleteStumsgByUsernameAndName(username, name);
            
            if (result == GlobalEnum.ErrorCode.OK) {
                msg.setErrorCode(GlobalEnum.ErrorCode.OK);
                msg.setErrorMsg("成功删除名称为 " + name + " 的任务。");
                msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
            } else if (result == GlobalEnum.ErrorCode.USER_QUERY_FAILED) {
                msg.setErrorCode(GlobalEnum.ErrorCode.USER_QUERY_FAILED);
                msg.setErrorMsg("未找到名称为 " + name + " 的任务。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.UNKNOWN);
                msg.setErrorMsg("删除任务时发生未知错误。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.UNKNOWN);
            msg.setErrorMsg("服务器异常: " + e.toString());
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        }
        return msg;
    }

    @PutMapping("/stumsg/{username}/{msgname}")
    @Operation(summary = "Update a task by username and msgname.")
    public BasicMsg updateStumsgByUsernameAndMsgname(@PathVariable String username, @PathVariable String msgname, @RequestBody stumsg stumsg) {
        BasicMsg msg = new BasicMsg();
        try {
            // 检查任务名称是否为空
            System.out.println("接收到的任务名称: " + msgname);
            if (msgname == null || msgname.trim().isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.USER_QUERY_FAILED);
                msg.setErrorMsg("任务名称不能为空。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
                return msg;
            }
            
            // 先查询该用户的所有任务
            System.out.println("查询用户 " + username + " 的所有任务");
            List<stumsg> taskList = stumsgService.getStumsgByUsername(username);
            System.out.println("找到 " + (taskList == null ? 0 : taskList.size()) + " 个任务");
            if (taskList != null) {
                for (stumsg task : taskList) {
                    System.out.println("任务: " + task.getMasname());
                }
            }
            if (taskList == null || taskList.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.USER_QUERY_FAILED);
                msg.setErrorMsg("未找到用户名为 " + username + " 的任务。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
                return msg;
            }
            
            // 不在这里设置所有任务列表，稍后只返回更新后的任务
            
            // 执行更新操作
            GlobalEnum.ErrorCode result;
            System.out.println("准备更新任务，用户名: " + username + ", 原任务名: " + msgname);
            System.out.println("更新内容: " + stumsg.getMassion());
            
            // 检查是否需要更新任务名称
            String newMsgname = stumsg.getMasname();
            boolean updateName = newMsgname != null && !newMsgname.trim().isEmpty() && !newMsgname.equals(msgname);
            
            if (updateName) {
                System.out.println("更新任务名称: " + msgname + " -> " + newMsgname);
            }
            
            if (stumsg.getMassiontime() != null) {
                // 如果提供了时间参数，则同时更新内容和时间
                System.out.println("更新时间: " + stumsg.getMassiontime());
                if (updateName) {
                    // 更新任务名称、内容和时间
                    result = stumsgService.updateStumsgByUsernameAndMsgname(username, msgname, newMsgname, stumsg.getMassion(), stumsg.getMassiontime());
                } else {
                    // 只更新内容和时间
                    result = stumsgService.updateStumsgByUsernameAndMsgname(username, msgname, stumsg.getMassion(), stumsg.getMassiontime());
                }
            } else {
                // 如果没有提供时间参数，则只更新内容
                System.out.println("不更新时间");
                if (updateName) {
                    // 更新任务名称和内容
                    result = stumsgService.updateStumsgByUsernameAndMsgname(username, msgname, newMsgname, stumsg.getMassion(), new Date());
                } else {
                    // 只更新内容
                    result = stumsgService.updateStumsgByUsernameAndMsgname(username, msgname, stumsg.getMassion());
                }
            }
            System.out.println("更新结果: " + result);
            
            if (result == GlobalEnum.ErrorCode.OK) {
                // 查询更新后的任务
                String finalMsgname = updateName ? newMsgname : msgname;
                List<stumsg> updatedTasks = stumsgService.getStumsgByUsername(username);
                stumsg updatedTask = null;
                if (updatedTasks != null) {
                    for (stumsg task : updatedTasks) {
                        if (task.getMasname().equals(finalMsgname)) {
                            updatedTask = task;
                            break;
                        }
                    }
                }
                
                // 设置更新后的任务到响应中
                List<stumsg> resultData = new ArrayList<>();
                if (updatedTask != null) {
                    resultData.add(updatedTask);
                }
                msg.setData(resultData);
                
                msg.setErrorCode(GlobalEnum.ErrorCode.OK);
                if (updateName) {
                    if (stumsg.getMassiontime() != null) {
                        msg.setErrorMsg("成功将任务名称从 " + msgname + " 更新为 " + newMsgname + "，并更新了内容和时间。");
                    } else {
                        msg.setErrorMsg("成功将任务名称从 " + msgname + " 更新为 " + newMsgname + "，并更新了内容。");
                    }
                } else {
                    if (stumsg.getMassiontime() != null) {
                        msg.setErrorMsg("成功更新名称为 " + msgname + " 的任务内容和时间。");
                    } else {
                        msg.setErrorMsg("成功更新名称为 " + msgname + " 的任务内容。");
                    }
                }
                msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
            } else if (result == GlobalEnum.ErrorCode.USER_QUERY_FAILED) {
                msg.setErrorCode(GlobalEnum.ErrorCode.USER_QUERY_FAILED);
                msg.setErrorMsg("未找到名称为 " + msgname + " 的任务。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.UNKNOWN);
                msg.setErrorMsg("更新任务时发生未知错误。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.UNKNOWN);
            msg.setErrorMsg("服务器异常: " + e.toString());
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        }
        return msg;
    }
}
